package com.eedi.framework.mail.service;

import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.ReUtil;
import cn.hutool.core.util.StrUtil;
import com.google.common.annotations.VisibleForTesting;
import com.eedi.framework.common.util.object.BeanUtils;
import com.eedi.framework.mail.controller.sys.vo.template.MailTemplatePageReq;
import com.eedi.framework.mail.controller.sys.vo.template.MailTemplateSaveReq;
import com.eedi.framework.mail.dal.SysMaillCacheKeyConstants;
import com.eedi.framework.mail.dal.dataobject.SysMailTemplateDO;
import com.eedi.framework.mail.dal.mapper.SysMailTemplateMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;
import com.eedi.framework.common.pojo.PageResult;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

import static com.eedi.framework.common.exception.util.ServiceExceptionUtil.exception;
import static com.eedi.framework.mail.enums.SysMailErrorCodeConstants.SYS_MAIL_TEMPLATE_CODE_EXISTS;
import static com.eedi.framework.mail.enums.SysMailErrorCodeConstants.SYS_MAIL_TEMPLATE_NOT_EXISTS;


/**
 * 邮箱模版 Service 实现类
 *
 * @author zybourn
 * @since 2022-03-21
 */
@Service
@Validated
@Slf4j
public class SysMailTemplateServiceImpl implements SysMailTemplateService {

    /**
     * 正则表达式，匹配 {} 中的变量
     */
    private static final Pattern PATTERN_PARAMS = Pattern.compile("\\{(.*?)}");

    @Resource
    private SysMailTemplateMapper sysMailTemplateMapper;

    @Override
    public String createMailTemplate(MailTemplateSaveReq createReqVO) {
        // 校验 code 是否唯一
        validateCodeUnique(null, createReqVO.getCode());

        // 插入
        SysMailTemplateDO template = BeanUtils.toBean(createReqVO, SysMailTemplateDO.class);
        template.setParams(parseTemplateContentParams(createReqVO.getContent()));
        sysMailTemplateMapper.insert(template);
        return template.getSysMailTemplateId();
    }

    @Override
    @CacheEvict(cacheNames = SysMaillCacheKeyConstants.NOTIFY_TEMPLATE,
            allEntries = true) // allEntries 清空所有缓存，因为可能修改到 code 字段，不好清理
    public void updateMailTemplate(@Valid MailTemplateSaveReq updateReqVO) {
        // 校验是否存在
        validateMailTemplateExists(updateReqVO.getId());
        // 校验 code 是否唯一
        validateCodeUnique(updateReqVO.getId(), updateReqVO.getCode());
        // 更新
        SysMailTemplateDO updateObj = BeanUtils.toBean(updateReqVO, SysMailTemplateDO.class);
        updateObj.setParams(parseTemplateContentParams(updateReqVO.getContent()));

        sysMailTemplateMapper.updateById(updateObj);
    }

    @VisibleForTesting
    void validateCodeUnique(String id, String code) {
        SysMailTemplateDO template = sysMailTemplateMapper.selectByCode(code);
        if (template == null) {
            return;
        }
        // 存在 template 记录的情况下
        // 新增时，说明重复
        if (id == null
                || ObjUtil.notEqual(id, template.getSysMailTemplateId())) {
            // 更新时，如果 id 不一致，说明重复
            throw exception(SYS_MAIL_TEMPLATE_CODE_EXISTS);
        }
    }

    @Override
    @CacheEvict(cacheNames = SysMaillCacheKeyConstants.NOTIFY_TEMPLATE,
            allEntries = true) // allEntries 清空所有缓存，因为 id 不是直接的缓存 code，不好清理
    public void deleteMailTemplate(String id) {
        // 校验是否存在
        validateMailTemplateExists(id);

        // 删除
        sysMailTemplateMapper.deleteById(id);
    }

    private void validateMailTemplateExists(String id) {
        if (sysMailTemplateMapper.selectById(id) == null) {
            throw exception(SYS_MAIL_TEMPLATE_NOT_EXISTS);
        }
    }

    @Override
    public SysMailTemplateDO getMailTemplate(String id) {
        return sysMailTemplateMapper.selectById(id);
    }

    @Override
    @Cacheable(value = SysMaillCacheKeyConstants.MAIL_TEMPLATE, key = "#code", unless = "#result == null")
    public SysMailTemplateDO getMailTemplateByCodeFromCache(String code) {
        return sysMailTemplateMapper.selectByCode(code);
    }

    @Override
    public PageResult<SysMailTemplateDO> getMailTemplatePage(MailTemplatePageReq pageReqVO) {
        return sysMailTemplateMapper.selectPage(pageReqVO);
    }

    @Override
    public List<SysMailTemplateDO> getMailTemplateList() {
        return sysMailTemplateMapper.selectList();
    }

    @Override
    public String formatMailTemplateContent(String content, Map<String, Object> params) {
        return StrUtil.format(content, params);
    }

    @VisibleForTesting
    public List<String> parseTemplateContentParams(String content) {
        return ReUtil.findAllGroup1(PATTERN_PARAMS, content);
    }

    @Override
    public long getMailTemplateCountByAccountId(String accountId) {
        return sysMailTemplateMapper.selectCountByAccountId(accountId);
    }

}
